package com.hgyc.mom.common.util;


import javax.crypto.Cipher;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

public class RsaUtil {
    public static final String KEY_ALGORITHM = "RSA";
    private static final String PUBLIC_KEY = "-----BEGIN PUBLIC KEY-----\n" +
            "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCjkcuq31iyZnGA5NgcGcrBWyqe\n" +
            "0ycOvbuSG+nz8KjdwOHGZTFCQZE9lk8f9DmLXT1NPukWqIrtQVrr/ZQolUedP1RV\n" +
            "PaxwKTEhucpR1EYFr6M0w8OucOUi7SeyKVFMDSngc2tBzoHInGm87WwmJ2DskM47\n" +
            "mr2MSJcr9pi261PxiQIDAQAB\n" +
            "-----END PUBLIC KEY-----";
    private static final String PRIVATE_KEY = "-----BEGIN PRIVATE KEY-----\n" +
            "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAKORy6rfWLJmcYDk\n" +
            "2BwZysFbKp7TJw69u5Ib6fPwqN3A4cZlMUJBkT2WTx/0OYtdPU0+6Raoiu1BWuv9\n" +
            "lCiVR50/VFU9rHApMSG5ylHURgWvozTDw65w5SLtJ7IpUUwNKeBza0HOgcicabzt\n" +
            "bCYnYOyQzjuavYxIlyv2mLbrU/GJAgMBAAECgYEAhm+F3WLEG5xnHXD4zd/E7TZo\n" +
            "yTDyoQL/7w5SMtRRdjDZX5475iDNprirP7ASu6BeieZy3NSZmnZkrCE2bESFHj/H\n" +
            "V2bkKJ7OqIQ3H8w7zuYeW8IA7GQSwgZ77qqNgUzjNPuu8MvAOSHHv6DW4aKy7f/H\n" +
            "a8pFsd1R9xnwfJT2roECQQDY0N+LQ4zeuK2ejubo91nHsd3OlZAaSYF6L3FUY0Kz\n" +
            "zjIDsiqDoBrnvOZX1qSiBAUzR6/qJ6H75UGKeQMRt7INAkEAwSFxmVYlPpK60CQX\n" +
            "XpwlEm0NpnP40z8/O7InoW27qM1RvqznGzKQwwFQ0jxVVQ29QzBVYwOqB1NCO+BT\n" +
            "0cMqbQJAUM/RckvUNrNo6v9ia5S+HuNZxAUU9+dL3inOuOBiXThOhfgjRnonbRaI\n" +
            "WFcFd+m9snZWyBTLmGLDwgQGs9TfBQJAZEtr5Qd5m/8zCLhVcoqALgt4FUMQqxOj\n" +
            "UOr57blAxS6rDuxXsCYYS0y5nhQ69EqISQYmsZ7Lg7ZXJSUgIkTKGQJBALZkYHhc\n" +
            "/lduWOaS/1lWts2uore+2MVxqdgKHVy9mGntVKW52dTUrfUKPPW+zBRiGJPAPq+T\n" +
            "C68C3PIVAjLbQTI=\n" +
            "-----END PRIVATE KEY-----";

    public static PrivateKey getPrivateKeyFromPEM(String pemPrivateKey) throws Exception {
        // 去除 PEM 头部和尾部，并去除换行符
        String privateKeyContent = pemPrivateKey
                .replace("-----BEGIN PRIVATE KEY-----", "")
                .replace("-----END PRIVATE KEY-----", "")
                .replaceAll("\\s", "");

        // Base64 解码
        byte[] decodedKey = Base64.getDecoder().decode(privateKeyContent);

        // 根据 PKCS#8 规范生成私钥对象
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(decodedKey);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        return keyFactory.generatePrivate(keySpec);
    }

    public static String decrypt(String encryptedDataString) throws Exception {
        byte[] encryptedDataBytes = Base64.getDecoder().decode(encryptedDataString);

        PrivateKey privateKey = RsaUtil.getPrivateKeyFromPEM(PRIVATE_KEY);

        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        cipher.init(Cipher.DECRYPT_MODE, privateKey);

        byte[] decryptedData = cipher.doFinal(encryptedDataBytes);
        return new String(decryptedData, "UTF-8");
    }

    public static String encrypt(String content) throws Exception {
        // 去除PEM格式中的首尾标识和换行符
        String publicKeyPEM = PUBLIC_KEY.replace("-----BEGIN PUBLIC KEY-----", "")
                .replace("-----END PUBLIC KEY-----", "")
                .replaceAll("\\s", "");

        // 将PEM格式的公钥转换为PublicKey对象
        byte[] publicKeyBytes = Base64.getDecoder().decode(publicKeyPEM);
        X509EncodedKeySpec spec = new X509EncodedKeySpec(publicKeyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PublicKey publicKey = keyFactory.generatePublic(spec);

        // 加密数据
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        byte[] encryptedBytes = cipher.doFinal(content.getBytes());
        return Base64.getEncoder().encodeToString(encryptedBytes);
    }

    public static void main(String[] args) throws Exception {
        // JSEncrypt 加密后的内容
//        String encryptedDataString = "A6PEWCGei5ZPQilDONB5TeCYoNzni9d2I5znTnYjzAPQJrwEcwYJIOonLaGZZIeNYjbC6w9WpGaerOBA8I8K+CArFYJVcIkf4aARxMCyxXUzMhc4hwO3QutHSLRYP0Ftfr56hQCf2SLy8PAfAbQhpoMWb21FIqSevoUHk2i0G34=";

        String content = "since@1989";
        String encryptedDataString = RsaUtil.encrypt(content);
        System.out.println("Encrypted string: " + encryptedDataString);

        String decryptedString = RsaUtil.decrypt(encryptedDataString);
        System.out.println("Decrypted string: " + decryptedString);
    }

    public static String getPublicKey() {
        return PUBLIC_KEY;
    }
}

